package base

import (
	"gitee.com/dayu1985/framework/context"
	"reflect"
	"github.com/chinahdkj/xorm"
	"github.com/go-redis/redis"
	"fmt"
	"gitee.com/dayu1985/can_api/controller/app"
)

type Service struct {
	*xorm.Engine
	Redis  *redis.Client
	Mgo    *Mongo
	Prefix string `json:"prefix"`
	Config *context.Configuration
}

var Serve *Service

func NewService() *Service {
	Serve = new(Service)

	initMysql()
	initMongo()

	addr := app.MustValue("database", "redis", "")
	pwd := app.MustValue("database", "redis.pwd", "")
	db, _ := app.MustInt("database", "redis.db")

	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: pwd, // no password set
		DB:       db,  // use default DB
	})

	pong, err := client.Ping().Result()
	fmt.Println(pong, err)
	Serve.Redis = client

	return Serve
}

func RegisterService(s interface{}) {
	sty := reflect.TypeOf(s)
	svl := reflect.ValueOf(s)
	if sty.Kind() != reflect.Ptr || sty.Elem().Kind() != reflect.Struct {
		panic("传入对象必须为指针类型并且指针指向的是struct对象")
	}
	sty = sty.Elem()
	svl = svl.Elem()

	//找到service实例
	var nty reflect.Type
	var nvl reflect.Value
	for i := 0; i < sty.NumField(); i++ {
		ty := sty.Field(i).Type
		if ty.String() == "*base.Service" {
			nty = ty
			nvl = svl.Field(i)
		}
	}
	if nty == nil {
		panic("没有找到service对象，或者继承的service对象不为指针类型")
	}

	nty = nty.Elem()

	nvl.Set(reflect.ValueOf(Serve))
}
